<?php
/**
 * 公用控制器
 */
class BaseAction extends Action{
	public $accountId;
	public $userId;
	
	public function _initialize(){

        /*if(!IS_AJAX){
            if(!session('?accountId')){
                $this->error('账号ID参数错误');
            }

            $this->accountId = session('accountId');
            $this->login();
            $this->auth();
        }
        $this->userId = session('userId');*/
	}
	
	/**
	 * 用户登陆
	 */
	public function login($ifAuth=0)
	{
		if (in_array($_SERVER['SERVER_ADDR'], array('127.0.0.1'))) {
            session('userId', 3209494);
            session('accountId', 60);
            session('wechatId', 60);
            session('wechatUserId', 96221);
			$this->wechatId = session('wechatId');
			$this->userId = session('userId');
			$this->accountId = session('accountId');
		}

		//新功能提醒
		$this->newtip();
		// wechatId和accountId对应关系确认
		if ($this->isWechatBrower() && session('?wechatId')) {
			$mWechat = D('Wechat/Wechat');
			$wechatAccountId = $mWechat->getFieldByWechatId(session('wechatId'), 'account_id');
			if($wechatAccountId != $this->accountId){
				$this->logout();
			}
		}
		//
		if($this->isAlipayBrower() && session('?alipayId')){
			$alipayWechatId = M('Alipay')->getFieldByAlipayId(session('alipayId'),'account_id');
			if($alipayWechatId != $this->accountId){
				$this->logout();
				session('alipayId',null);
				session('alipayUserId',null);
			}
		}
		if(session('accountId') != $this->accountId){
			$this->logout();
		}

		if(!$this->isLogin()){
            // 记录用户访问动作
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
            $redirectUrl = $protocol.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
			session('redirectUrl', $redirectUrl);

			// 用户授权登陆
			if($this->isWechatBrower()){
				$this->wechatLogin();
			}elseif($this->isAlipayBrower()){
				$this->alipayLogin();
			}else{
				$this->error('用户登陆暂只支持微信和支付宝登陆，请用微信或支付宝重新打开');
			}
		} else {
            $userId = M('WechatUser')->where(array('wechat_user_id'=>$_SESSION['wechatUserId']))->getField('user_id');
            session('userId',$userId);
        }

        $this->userId = session('userId');
		//工商,滨江清除用户的重复数据
		if ($this->isWechatBrower() && $this->userId > 0){
			if ($this->accountId == 2 || $this->accountId == 17) {
				$this->clearSameUser();
			}
		}
        //如果用户默认需要注册
        if ($ifAuth != 1) 
        {
            $data = M('global_set')->where(array('account_id' => $this->accountId))->field('reg_enable')->find();
            if ($data && $data['reg_enable'] == 0) {  //如果不需要注册
                $ifAuth = 1;
            } else {    //需要注册
                $ifAuth = 0;
            }

            if ($ifAuth == 0) { //如果用户需要注册，就到注册页面中去
                $this->auth();
            } else {    //如果用户不需要注册，就自动添加数据进去，用来宾的身份
                $regService = Service("UserRegister");
                $userExists = $regService->userExists(session('userId'),$this->accountId);
                if (!$userExists) {
                    $regService->userBaseData = array(
                        'status' => 2,
                        'type' => 2,
                        'account_id' => $this->accountId,
                        'avatar' => session('wx_header'),
                        'origin' => 'register'
                    );

                    if($this->isAlipayBrower()){
                    	$regService->wechatUserData = array(
                        	'alipay_user_id' => session('alipayUserId'),
                        	'is_alipay'  	 =>	1               
                    	);
                    }else{
                    	$regService->wechatUserData = array(
                        	'wechat_user_id' => session('wechatUserId'),
                        	'is_alipay'  	 =>	0              
                    	);
                    }
                    
                    $regService->save();    //保存用户信息

                } else {

                    $wechatUserData = array(
                        'wechat_user_id' => session('wechatUserId'),
                        'user_id' => session('userId')
                    );
                    $regService->saveWechatUser($wechatUserData);
                }
            }
        }

        if($this->userId) {
            $user_type = D('User')->where('user_id ='.$this->userId)->field('type')->select();
            session('userType',$user_type[0]['type']);
        }
	}


	/**
	 * 新功能提醒
	 */
	public function newtip(){
		$path = GROUP_NAME.MODULE_NAME.ACTION_NAME;
		$day = time()-86400*7;
		$condition['path'] = strtolower($path);
		$condition['cut_off'] = 0;
		$condition['create_time'] = array('egt',$day);
		$list = D('Features')->where($condition)->select();
		if($list){
			$cok = $this->g_cookie(strtolower($path));
			$uri = $this->g_cookie('comm_uri');
			if(!is_array($cok)){
				$this->s_cookie(strtolower($path),$list);
				$this->s_cookie('comm_uri',__SELF__);
				$this->s_cookie('comm_path',strtolower($path));
				$this->redirect('Base/Common/comm','', 0, '页面跳转中...');
			}
		}
	}

	/**
	 * 获取cookie
	 */
	public function g_cookie($name){
		$ck = $_COOKIE[$name];
		$cookie =  unserialize($ck);
		return $cookie;
	}
	/**
	 * 设置cookie
	 */
	public function s_cookie($name,$cookie){
		$coke = serialize($cookie);
		setcookie($name,$coke,time ()+ 2678400,'/');
	}

	/**
	 * 判断是否是微信浏览器
	 * @return boolean
	 */
	public function isWechatBrower()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') != false) {
			return true;
		} else {
			return false;
		}
	}

	public function logout(){
		// 销毁登陆信息
		session('accountId', null);
		session('userId', null);
		session('wechatUserId', null);
		session('wechatId', null);
        session('openId',null);
        session('accountEnName',null);
	}

	/**
	 * 判断是否是支付宝浏览器
	 * @return boolean
	 */
	public function isAlipayBrower()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') != false) {
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 判断用户是否登陆
	 * @return boolean
	 */
	public function isLogin()
	{
//		if ($this->accountId == session('accountId') &&
//            ($_SESSION['alipayUserId'] || $_SESSION['wechatUserId']) &&
//            $_SESSION['userId']
//        ) {
//			return true;
//		}else{
//			return false;
//		}

        if ($this->accountId == session('accountId') &&
            ($_SESSION['alipayUserId'] || $_SESSION['wechatUserId'])
        ) {
            return true;
        }else{
            return false;
        }
	}

	/**
	 * 微信网页授权登陆
	 */
	public function wechatLogin(){
		$authCode = $this->_get('code');
		$mWechat = D('Wechat/Wechat');
		$wechatInfo = $mWechat->getByAccountId($this->accountId);

		session('wechatId', $wechatInfo['wechat_id']);
		session('accountId', $wechatInfo['account_id']);
		if(!$authCode){
			// 模拟登录获取code
			//echo '++++'.$this->accountId;die();
			$appid = $mWechat->getFieldByAccountId($this->accountId,'appid');
//            wLog(date('Y-m-d H:i:s').'data:'.var_export($this->accountId,true),'wechatapi');
//            wLog(date('Y-m-d H:i:s').'data:'.var_export($appid,true),'wechatapi');
			$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.
					'&accountId='.$this->accountId.'&redirect_uri='.urlencode(session('redirectUrl')).
					'&response_type=code&scope=snsapi_base&state=repair#wechat_redirect';

			session('snsapiBase',true);
			header('Location: '.$url);
			exit;
		}else{
			// 获取公众号信息
			$mWechatUser = D('Wechat/WechatUser');
			
			// 引用微信接口文件
			vendor('Wechat.WechatApi');
			$cWechat = new WechatApi($wechatInfo['wechat_id']);
			if(session('?snsapiBase')){
				// 获取用户openid
				$info = $cWechat->getUserInfoByAuth($authCode, false);
				if($info['status'] != 'S'){
					$this->error('用户信息获取错误，请稍后再试');
				}

				$openid = $info['data'];
				$condition = array(
						'wechat_id' => $wechatInfo['wechat_id'],
						'openid' => $openid,
				);
				$wechatUserInfo = $mWechatUser->getInfo($condition);
				session('snsapiBase', null);
				if(!$wechatUserInfo){
					// 用户首次访问，重新跳转网页授权获取用户信息
					$redirectUrl = session('redirectUrl');
					$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$wechatInfo['appid'].'&redirect_uri='.urlencode($redirectUrl).'&response_type=code&scope=snsapi_userinfo&state=repair#wechat_redirect';
					header('Location: '.$url);
                    //            wLog(date('Y-m-d H:i:s').'data:'.var_export($url,true),'wechatapi');
					exit;
				}elseif(!$wechatUserInfo['subscribe']){
					// 未关注的老用户的关注状态验证
					$res = $cWechat->getUserInfo($openid);
					if($res['status'] == 'S'){
						if(!$wechatUserInfo['subscribe'] && $res['data']['subscribe']){
							$update = array(
                                    'wechat_id' => session('wechatId'),
									'wechat_user_id' => $wechatUserInfo['wechat_user_id'],
									'type' => 1,
									'subscribe' => 1,
									'last_subscribe_time' => $res['data']['subscribe_time'],
									'group_id' => $res['data']['groupid'],
                                    'avatar' => $res['data']['headimgurl']
							);
							$mWechatUser->update($update);
						}
					}
				}
			}else{
				// 网页授权获取新用户信息
				$res = $cWechat->getUserInfoByAuth($authCode, false);
				$openid = $res['data'];
				$info = $cWechat->getUserInfo($openid);
				$result = $info['data'];
				//$openid = $result['openid'];
				if($info['status'] == 'F'){
					$this->error($info['message']);
				}elseif(!$openid){
					$this->error('网页授权获取用户信息失败，请稍后重试');
				}else {
				    session('wx_header',$result['headimgurl']);
				}

				// 插入用户信息
				$result['wechat_id'] = session('wechatId');
				$result['avatar'] = $result['headimgurl'];
				$wechatUserInfo = $mWechatUser->update($result);

                if(empty($wechatUserInfo)){
					$this->error('用户信息更新错误，请稍后再试');
				}
			}

			// 登陆成功
			session('wechatUserId', $wechatUserInfo['wechat_user_id']);
			session('userId', $wechatUserInfo['user_id']);
            session('openId', $openid);
            $accountEnName = D('Account')->where(array('account_id'=>$this->accountId))->getField('account_en_name');
            session('accountEnName',$accountEnName);

			// 重置至用户访问的地址，防止authCode失效，刷新失败
			if(session('?redirectUrl')){
				header('Location: '.session('redirectUrl'));
				exit;
			}

		}
		
	}

	/**
	 * 支付宝网页授权登陆
	 */
	public function alipayLogin()
	{
		$authCode = $this->_get('auth_code');
		$mAlipay = D('Alipay/Alipay');
		if (!$authCode) {
			$appid = $mAlipay->getFieldByAccountId($this->accountId, 'appid');
			$url = 'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=' . $appid . '&scope=auth_userinfo&redirect_uri=' . session('redirectUrl');
			header('Location: ' . $url);
			exit;
		}else{
			$mAlipayUser = D('Alipay/AlipayUser');
			// 获取支付宝用户信息
			$alipayId = $mAlipay->getFieldByAccountId($this->accountId, 'alipay_id');
			vendor('Alipay.AlipayApi');
			$cAlipay = new AlipayApi($alipayId);
			$return = $cAlipay->getUserInfoByAuth($authCode);
			if ($return['status'] == 'F') {
				$this->error($return['message']);
			}

			// 转换用户信息数据包
			$update = $return['data'];
			$originalAlipayUserId = $update['alipay_user_id'];
			$alipayUserInfo = $mAlipayUser->getByOriginalAlipayUserId($originalAlipayUserId);
			if ($alipayUserInfo) {
				$update['alipay_user_id'] = $alipayUserInfo['alipay_user_id'];
			} else {
				$update['original_alipay_user_id'] = $update['alipay_user_id'];
				$update['original_user_id'] = $update['user_id'];
				unset($update['alipay_user_id']);
			}
			unset($update['user_id']);
			$update['sex'] = $update['gender'];
			$update['nickname'] = $update['nick_name'];

			// session存储账号ID，作为数据插入前分表判断依据
			session('accountId', $this->accountId);
			// session存储服务窗ID
			session('alipayId', $alipayId);
			$update['alipay_id'] = $alipayId;

			// 更新用户信息
			$alipayUserInfo = $mAlipayUser->update($update);
			// 登陆成功
			session('alipayUserId', $alipayUserInfo['alipay_user_id']);
			//重新查一遍查询包括user_id的值
			$alipayUserInfo = $mAlipayUser->getByAlipayUserId($alipayUserInfo['alipay_user_id']);
			session('userId', $alipayUserInfo['user_id']);			
		}
	}
	
	/**
	 * 用户认证验证
	 */
	public function auth(){
		$mUser = D('User');
		$userInfo = $mUser->getByPk(session('userId'));
		if (!$userInfo['real_name'] || !$userInfo['mobile']){
			$userInfo['type'] = 0;
//			$mUser->where(array('user_id'=>session('userId')))->save(array('status'=>0,'type'=>0));
		}
		$authUrl = U('base/user/register',array('account_id' => $this->accountId,'type'=>$userInfo['type']));
		$presentUrl = GROUP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME; //当前链接URL
		if( ($userInfo['status'] !=2 || !session('userId') ) && $presentUrl != 'Base/User/register') {
			//echo $authUrl;die();
			// 用户未认证
			$this->redirect($authUrl);
			exit;
		}
//		if(!$userInfo['status'] && $presentUrl != 'Base/User/register'){
//			$this->redirect($authUrl);
//			exit;
//		}
	}

	/**
	 * 是否是丁丁浏览器
	 * @return string
	 */
	public function isDingBrowser()
	{
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'DingTalk') != false) {
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * 获取订单编号
	 * @param string $moduleName
	 * @return array
	 */
	public function getOrderSn($moduleName){
		// 14位时间戳
		$datatime = date('YmdHis');
		// 3位模块ID
		$moduleData = $this->getModuleIdByModuleName($moduleName);
		if($moduleData['status'] == 'S'){
			$moduleId = str_pad($moduleData['data'], 3, '0', STR_PAD_LEFT);
		}else{
			return $moduleData;
		}
		// 2位账号ID
		$accountShortId = str_pad(substr(session('accountId'), -2), 2, '0', STR_PAD_LEFT);
		// 4位用户ID
		$userFullId = str_pad(substr(session('userId'), -4), 4, '0', STR_PAD_LEFT);
		// 1位支付方式
		if($this->isWechatBrower()){
			$payType = 1;
		}elseif($this->isAlipayBrower()){
			$payType = 2;
		}else{
			$payType = 0;
		}
		// 4位随机数
		$rand = rand(1000, 9999);
		$orderSn = $datatime.$moduleId.$accountShortId.$userFullId.$payType.$rand;
		if(strlen($orderSn) != 28){
			return array('status' => 'F', 'message'=>'订单编号生成异常');
		}
		return array('status' => 'S', 'data' => $orderSn);
	}
	
	/**
	 * 通过模块名称获取模块ID
	 * @param string $moduleName
	 * @return array
	 */
	public function getModuleIdByModuleName($moduleName){
		$moduleId = D('Module')->getFieldByModuleName($moduleName, 'module_id');
		if($moduleId){
			return array('status' => 'S', 'data' => $moduleId);
		}else{
			return array('status' => 'F', 'message' => '模块不存在');
		}
	}
	
	/**
	 * 订单支付
	 * @param array $payData
	 * @return array 
	 */
	public function pay($payData){
		// 数据包不为空验证
		if(empty($payData)){
			return array('status' => 'F', 'message' => '支付数据包不能为空');
		}
        
		if($this->isWechatBrower()){
            return $this->wechatPay($payData);
		}elseif($this->isAlipayBrower()){
			return $this->alipayPay($payData);
		}else{
//			return $this->alipayPay($payData);
			return array('status' => 'F', 'message' => '当前支付只支持微信或支付宝钱包支付');
		}
	}
	
	/**
	 * 微信支付
	 * @param array $payData
	 * @return array 
	 */
	public function wechatPay($payData){
        if (isset($payData['is_special']) && $payData['is_special'] == '0') {
            $payService = Service('Pay/WxPay');
            return $payService->wechatNormalPay($payData); 
        }
        
		$verifyField = array(
				'parentAppid',			// 母商户ID
				'parentMchId',			// 母商户商户ID
				'parentKey',			// 母商户KEY
				'subOpenid',			// 用户在子商户下的微信openid
				'subAppid',				// 子商户ID
				'subMchId',				// 子商户商户ID
				'orderName',			// 订单名称
				'orderSn',				// 订单编号
				'orderAmount',			// 订单金额
		);
		foreach($verifyField as $key => $value){
			if(empty($payData[$value])){
				return array('status' => 'F', 'message' => $value . '不能为空');
			}
		}
		// 组建支付传输数据包
		$notifyUrl = C('site_url').U('wechat/wechat_pay/notify');
		vendor('Wechat.WechatPay');
		$cWechatPay = new WechatPay($payData['parentAppid'], $payData['parentMchId'], $payData['parentKey'], $notifyUrl);
		$cWechatPay->setParameter("sub_openid", $payData['subOpenid']);
		$cWechatPay->setParameter("sub_appid", $payData['subAppid']);
		$cWechatPay->setParameter("sub_mch_id", $payData['subMchId']);
		$cWechatPay->setParameter("body", $payData['orderName']);
		$cWechatPay->setParameter("out_trade_no", $payData['orderSn']);
		$cWechatPay->setParameter("total_fee", $payData['orderAmount'] * 100);
		$cWechatPay->setParameter("notify_url", $notifyUrl);
		$cWechatPay->setParameter("trade_type", "JSAPI"); 
		$prepayData = $cWechatPay->getPrepayId();
		if($prepayData['status'] == 'S'){
			$prepayId = $prepayData['data'];
		}else{
			return array('status' => 'F', 'message' => $prepayData['message'] ? $prepayData['message'] : '微支付系统繁忙，请联系管理员');
		}
		$cWechatPay->setPrepayId($prepayId);
		$jsApiParameters = $cWechatPay->getParameters();
		wLog('jsApiParam:'.var_export($jsApiParameters,true),'wxPay');

		return array('status' => 'S', 'data' => $jsApiParameters);
	}
	
	public function alipayPay($payData){
		$verifyField = array(
				'partner',				// 合作者支付宝账号ID
				'sellerId',				// 卖家支付宝用户号
				'returnUrl',			// 页面跳转同步通知页面路径
// 				'externToken',			// 手机支付宝token
				'orderName',			// 订单名称
				'orderDesc',			// 订单描述
				'orderSn',				// 订单编号
				'orderAmount',			// 订单金额
		);
		foreach($verifyField as $key => $value){
			if(empty($payData[$value])){
				return array('status' => 'F', 'message' => $value.'不能为空');
			}
		}
		$notifyUrl = C('site_url').U('alipay/alipay_pay/notify');
		$parameter = array(
				"service" => "alipay.wap.create.direct.pay.by.user",
				"partner" => trim($payData['partner']),
				"seller_id" => trim($payData['sellerId']),
				"payment_type" => 1,
				"notify_url" => $notifyUrl,
				"return_url" => $payData['returnUrl'],
				"out_trade_no" => $payData['orderSn'],
				"subject" => $payData['orderName'],
				"total_fee" => $payData['orderAmount'],
				"body" => $payData['orderDesc'],
				"it_b_pay" => '1d',
				"_input_charset" => 'UTF-8',
		);
		vendor('Alipay.AlipayPay');
		$cAlipayPay = new AlipayPay($this->accountId);
		$return = $cAlipayPay->pay($parameter);
	}

	/**
	*微信发红包
	 * @param int $accountId
	 * @param string $openid
	 * @param float $money      红包金额
	 * @param string $wishing  祝福语
	 * @param string $actName  活动名称
	 * @param string $remark   备注
	 * @return array $res
	 */
	public function sendRedToUser($accountId,$openid,$money,$wishing,$actName,$remark){
		if(!$accountId || !$openid || !$money){
			return array('status' => 'F','message' => '缺少必要的参数');
		}

		if(strlen($wishing) > 128){
			return array('status' => 'F','message' => '祝福语字数超过限制');
		}

		if(strlen($actName) > 32){
			return array('status' => 'F','message' => '活动名称字数超过限制');
		}

		if(strlen($remark) > 256){
			return array('status' => 'F','message' => '备注信息字数超过限制');
		}

		vendor('Wechat.WechatApi');
		$wechat = D('Wechat/Wechat')->getInfo(array('account_id' => $accountId));
		$weixin = new WechatApi($wechat['wechat_id']);

		$array['mch_billno'] = $wechat['parent_mch_id'] . date('YmdHis') .mt_rand(1000,9999);
		$array['mch_id'] = $wechat['parent_mch_id'];
		$array['sub_mch_id'] = $wechat['mch_id'];
		$array['wxappid'] = $wechat['parent_appid'];
		$array['msgappid'] = $wechat['appid'];
		$array['send_name'] = $wechat['wechat_name'];
		$array['re_openid'] = $openid;
		$array['total_amount'] = $money * 100;
		$array['min_value'] = $money * 100;
		$array['max_value'] = $money * 100;
		$array['wishing'] = $wishing;
		$array['act_name'] = $actName;
		$array['remark'] = $remark;
		$res = $weixin->send_redpacket($array);
		return $res;
	}

	/**
	 * 共用赋值与渲染
	 */
	public function view($data){
		$this->assign('data',$data);
		$this->display();
	}

	/**
	 * 新版支付订单支付
	 * @param string $orderSn  订单编号
	 * @param string $title    订单名称
	 * @param string $accountId  账号id
	 * @param string $notifyUrl  异步回调地址
	 * @param string $returnUrl  同步回调地址
     * @param string $returnUrl  微信分账（zym/wika 2017/8/7）
	 * @return array
	 */
	public function newPay($accountId = '',$orderSn='',$title='订单支付',$notifyUrl = '',$returnUrl = '',$ledger = array()){
		if(!isset($accountId)){
			$accountId = session('accountId');
		}
		$payFactory = Service('Pay/PayFactory');
		if($this->isWechatBrower()){
			return $payFactory->createObj('weixin',$accountId,$orderSn,$title,$notifyUrl,$returnUrl,$ledger);
		}elseif($this->isAlipayBrower()){
			return $payFactory->createObj('alipay',$accountId,$orderSn,$title,$notifyUrl,$returnUrl);
		}else{
//			return $this->alipayPay($payData);
			return array('status' => 'F', 'message' => '当前支付只支持微信或支付宝钱包支付');
		}
	}

	/**
	 * 清除重复的用户数据，避免用户支付串号
	 */
	public function  clearSameUser()
	{
		$condition = array(
				'user_id'=>session('userId'),
				'wechat_user_id'=>array('neq',session('wechatUserId'))
		);
		$count = D('Wechat/WechatUser')->where($condition)->count();
		if ($count > 0) {
			D('Wechat/WechatUser')->where($condition)->save(array('user_id' => 0));
		}
	}

	/**
	 * 是否需要强关判断
	 */
	public function focus($shorthand)
	{
		$id = M('AccountMenuFocus')->where(array('account_id'=>$this->accountId,'shorthand'=>$shorthand))->getField('id');
		if ($id){
			$subscribe = M('WechatUser')->where(array('wecaht_user_id'=>session('wechatUserId')))->getField('subscribe');
			if ($subscribe != 1){
				$url = U('/base/subscribe/index',array('account_id'=>$this->accountId));
				R($url);
			}
		}
	}
}
